package com.fnzn.entranceGuard.api;

import com.fnzn.entranceGuard.entity.User;
import com.fnzn.entranceGuard.feign.ApiToken;
import com.fnzn.entranceGuard.feign.UserInfoService;
import com.fnzn.entranceGuard.util.ConstantUtil;
import com.fnzn.entranceGuard.util.PhoneFormatCheckUtils;
import com.fnzn.entranceGuard.util.ResponseUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.ListUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author wf_sxf@163.com
 * @date 2018/5/23 17:34
 */
@Controller
@RequestMapping("guard")
public class LoginRest {

    @Autowired
    private UserInfoService userService;
    @Autowired
    private ApiToken apiToken;

    @Autowired
    public RedisTemplate redisTemplate;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseUtil login(@RequestBody User user) {
        ResponseUtil r = new ResponseUtil();
        try {
            List<User> list = userService.get(user.getUsername());
            if (list != null) {
                User u = list.get(0);
                //判断密码
                if (StringUtils.isNotBlank(u.getPassword()) && new BCryptPasswordEncoder().matches(user.getPassword(), u.getPassword())) {
                    r = apiToken.getUserToken(user);
                    return r;
                }
            }
            r.fail("500", "请输入正确的用户信息");
        } catch (Exception e) {
            e.printStackTrace();
            r.fail("500", e.getMessage());
        }
        return r;
    }

    @RequestMapping(value = "/freshToken", method = RequestMethod.POST)
    @ResponseBody
    public ResponseUtil freshToken(@RequestBody String token) {
        ResponseUtil r = new ResponseUtil();
        try {
            r = apiToken.refreshUserToken(token);
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            r.fail("500", e.getMessage());
        }
        return r;
    }

    /**
     * 第三方登录接口
     * @param user (openId & loginType)
     * @return
     */
    @RequestMapping(value = "/thirdPartyLogin", method = RequestMethod.POST)
    @ResponseBody
    public ResponseUtil openIdLogin(@RequestBody User user) {
        ResponseUtil r = new ResponseUtil();
        try {
            if(StringUtils.isNotBlank(user.getLoginType())){
                if(ConstantUtil.WeChat.equals(user.getLoginType())) {
                    List<User> list = userService.getByOpenId(user.getOpenId());
                    if(!ListUtils.isEmpty(list)) {
                        User u = list.get(0);
                        r = apiToken.getUserToken(u);
                        return r;
                    }
                    //todo 修改返回码
                    r.fail("501", "该微信未绑定手机号");
                    return r;
                } else if(ConstantUtil.QQ.equals(user.getLoginType()))  {
                    List<User> list = userService.getByQqId(user.getOpenId());
                    if(!ListUtils.isEmpty(list)) {
                        User u = list.get(0);
                        r = apiToken.getUserToken(u);
                        return r;
                    }
                    //todo 修改返回码
                    r.fail("501", "该QQ未绑定手机号");
                    return r;
                }
            }
            //todo 修改返回码
            r.fail("502", "未知登录方式");
        } catch (Exception e) {
            e.printStackTrace();
            r.fail("500", e.getMessage());
        }
        return r;
    }

    /**
     * 发送短信验证码接口
     * @param user (username)
     * @return
     */
    @RequestMapping(value="/sendMobileCode", method = RequestMethod.POST)
    @ResponseBody
    public ResponseUtil sendMobileCode(@RequestBody User user) {
        ResponseUtil r = new ResponseUtil();
        try{
            if(StringUtils.isBlank(user.getUsername())){
                r.fail("500", "手机号为空");
                return r;
            }

            if (!PhoneFormatCheckUtils.isPhoneLegal(user.getUsername())) {
                r.fail("500", "手机号格式错误");
                return r;
            }

            //随机数生成验证码
            int mobileCode = (int)((Math.random()*9+1)*100000);
            String content = new String("您的验证码是：" + mobileCode + "，请在1分钟内使用");
            //SendMsgUtil.sendSmsByAliDayu(user.getUsername(),content);

            ValueOperations<String,String> operation = redisTemplate.opsForValue();
            redisTemplate.delete(user.getUsername());
            operation.set(user.getUsername(), String.valueOf(mobileCode), 60, TimeUnit.SECONDS);

            //todo 修改返回码
            //r.ok("验证码发送成功" + mobileCode);
            r.ok(mobileCode);
        } catch(Exception e) {
            e.printStackTrace();
            r.fail("500", e.getMessage());
        }
        return r;
    }

    /**
     * 登录注册接口
     * @param user (username & mobileCode & openId & loginType)
     * @return
     */
    @RequestMapping(value="/signIn", method = RequestMethod.POST)
    @ResponseBody
    public ResponseUtil signIn(@RequestBody User user) {
        ResponseUtil r = new ResponseUtil();
        try{
            //todo 修改返回码
            if(StringUtils.isBlank(user.getUsername())){
                r.fail("500", "手机号为空");
                return r;
            }
            if (!PhoneFormatCheckUtils.isPhoneLegal(user.getUsername())) {
                r.fail("500", "手机号格式错误");
                return r;
            }
            if(StringUtils.isBlank(user.getMobileCode())){
                r.fail("500", "验证码为空");
                return r;
            }

            ValueOperations<String,String> operation = redisTemplate.opsForValue();
            String oldMobileCode = operation.get(user.getUsername());

            if(StringUtils.isBlank(oldMobileCode)) {
                r.fail("500", "验证码已过期或输入手机号与接收验证码手机号不一致");
                return r;
            }
            if(!oldMobileCode.equals(user.getMobileCode())) {
                r.fail("500", "验证码错误");
                return r;
            }

            //验证码验证正确：
            List<User> list = userService.get(user.getUsername());
            if(ListUtils.isEmpty(list)) {
                //手机号未注册
                if(ConstantUtil.NORMAL.equals(user.getLoginType())) {
                    //先注册:
                    user.setMobilePhone(user.getUsername());
                    String str = user.getUsername();
                    String name = str.substring(str.length()-4);
                    user.setName(name);
                    user.setPassword("111111");
                    userService.addUser(user);

                    //再登录
                    r = apiToken.getUserToken(user);
                    redisTemplate.delete(user.getUsername());
                    return r;
                } else if(ConstantUtil.WeChat.equals(user.getLoginType())) {
                    if(StringUtils.isBlank(user.getOpenId())) {
                        r.fail("500", "openId为空");
                        return r;
                    }
                    //先注册:
                    user.setMobilePhone(user.getUsername());
                    String str = user.getUsername();
                    String name = str.substring(str.length()-4);
                    user.setName(name);
                    user.setPassword("111111");
                    userService.addUser(user);

                    //再登录
                    r = apiToken.getUserToken(user);
                    redisTemplate.delete(user.getUsername());
                    return r;
                } else if(ConstantUtil.QQ.equals(user.getLoginType())) {
                    if(StringUtils.isBlank(user.getQqId())) {
                        r.fail("500", "qqId为空");
                        return r;
                    }
                    //先注册:
                    user.setMobilePhone(user.getUsername());
                    String str = user.getUsername();
                    String name = str.substring(str.length()-4);
                    user.setName(name);
                    user.setPassword("111111");
                    userService.addUser(user);

                    //再登录
                    r = apiToken.getUserToken(user);
                    redisTemplate.delete(user.getUsername());
                    return r;
                }
            } else {
                //手机号已注册
                if(ConstantUtil.NORMAL.equals(user.getLoginType())) {
                    //直接登录
                    r = apiToken.getUserToken(user);
                    redisTemplate.delete(user.getUsername());
                    return r;
                } else if(ConstantUtil.WeChat.equals(user.getLoginType())) {
                    User u = list.get(0);
                    if(StringUtils.isNotBlank(u.getOpenId())) {
                        r.fail("500", "该手机号已绑定微信");
                        return r;
                    }
                    u.setOpenId(user.getOpenId());
                    userService.updateUser(u);

                    r = apiToken.getUserToken(user);
                    redisTemplate.delete(user.getUsername());
                    return r;
                } else if(ConstantUtil.QQ.equals(user.getLoginType())) {
                    User u = list.get(0);
                    if(StringUtils.isNotBlank(u.getQqId())) {
                        r.fail("500", "该手机号已绑定QQ");
                        return r;
                    }
                    u.setQqId(user.getQqId());
                    userService.updateUser(u);

                    r = apiToken.getUserToken(user);
                    redisTemplate.delete(user.getUsername());
                    return r;
                }
            }
            r.fail("500", "登录类型未知");
        } catch(Exception e) {
            e.printStackTrace();
            r.fail("500", e.getMessage());
        }
        return r;
    }

}
